<?php

namespace Trawind\Basics\Traits\Console;

use InvalidArgumentException;
use Trawind\Helpers\UserHelper;
use Symfony\Component\Console\Input\InputOption;

trait SingleTenantConsole
{

    protected $tenant;


    protected function configure()
    {
        parent::configure();
        $this->addOption('tenant_id', 'N', InputOption::VALUE_REQUIRED, 'tenant_id');
    }

    final public function handle()
    {
        date_default_timezone_set("UTC");
        $tenant = config('tenancy.tenant_model')::where('tenant_id', $this->getTenantId())->firstOrFail();

        $this->tenant = $tenant;
        UserHelper::setConsoleTenantId($this->tenant->tenant_id);
        $tenant->run([$this, 'exec']);
    }

    protected function getTenantId()
    {
        if (is_null($tenantId = $this->option('tenant_id'))) {
            throw new InvalidArgumentException('tenant_id is required');
        }
        return $tenantId;
    }

    abstract public function exec();

}